package com.toilet.easyvideo.security;

import jakarta.annotation.Resource;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * 自定义认证
 */
@Component
public class SysUserAuthorizeProvider implements AuthenticationProvider {
    /**
     * 此处使用自定义认证
     */
    @Resource
    private SysUserAuthorizeService authorizeService;
    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String name = authentication.getName();
        String password = authentication.getPrincipal().toString();
        UserDetails userDetails = authorizeService.loadUserByUsername(name);
        if (passwordEncoder.matches(password, userDetails.getPassword())) {
            //密码匹配
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(name, password, userDetails.getAuthorities());
            //5存入SecurityContextHolder
            SecurityContextHolder.getContext().setAuthentication(token);
            return token;
        } else {
            //密码不匹配
            throw new BadCredentialsException("密码认证失败！");
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}
